<?php
require_once 'classes/View.php';
require_once 'classes/DB.php';
require_once 'config.php';

session_start();

global $pageOn;
$pageOn = basename($_SERVER['PHP_SELF']);

if (!isset($_SESSION['user']))
{
	header('Location: index.php');
}
else
{
	/*View*/ $view = new View();
	if (isset($_REQUEST['edit_btn']))
	{
		$_SESSION['category']->setName($_REQUEST['name']);
		$error = $_SESSION['category']->edit();
		if($error == "")
		{
			$view->data['notification'] = 'Edit successful';
		}
		else
		{
			$view->data['error'] = $error;
		}
	}
	else if (isset($_REQUEST['delete_btn']) || isset ($_REQUEST['up']))
	{
		/*Category*/ $parentCategory = new Category(DB::getInstance());
		$parentCategory->setCategoryId($_SESSION['category']->getParentId());
		$parentCategory->load();
		if (isset($_REQUEST['delete_btn']))
		{
			$_SESSION['category']->delete();
			$view->data['notification'] = 'Delete successful';
		}
		$_SESSION['category'] = $parentCategory;
	}
	else if (isset($_REQUEST['add_category_btn']))
	{
		/*Category*/ $category = new Category(DB::getInstance());
		$category->setName($_REQUEST['name']);
		$error = $_SESSION['category']->addCategory($category);
		if($error == "")
		{
			$view->data['notification'] = 'Add category successful';
		}
		else
		{
			$view->data['error'] = $error;
		}
	}
	else if (isset($_REQUEST['add_photo_btn']))
	{
		if ($_FILES['data']['size'] >= FILE_MAX_SIZE)
		{
			$view->data['error'] = 'Trying to upload too big file. Please try with smaller image.';
		}
		else if (strpos($_FILES['data']['type'], 'image') !== 0)
		{
			$view->data['error'] = 'Trying to upload a file which is not an image. Please try with image file.';
		}
		else
		{
			/*Photo*/ $photo = new Photo(DB::getInstance());
			$photo->setName($_REQUEST['name']);
			$photo->setDescription($_REQUEST['description']);
			$error = $_SESSION['category']->addPhoto($photo, $_FILES['data']['tmp_name']);
			if($error == "")
			{
				$view->data['notification'] = 'Photo added successfully';
			}
			else
			{
				$view->data['error'] = $error;
			}
		}
		
	}
	else if (isset($_REQUEST['category_id']))
	{
		/*Category*/ $childCategory = new Category(DB::getInstance());
		$childCategory->setCategoryId($_REQUEST['category_id']);
		$childCategory->load();
		$_SESSION['category'] = $childCategory;
	} 
	else if (isset($_REQUEST['root']) || !isset($_SESSION['category'])) 
	{
		$_SESSION['category'] = $_SESSION['user']->getRootCategory();
	}
	$view->display('category');
}
?>